package cn.zhxu.toys.cipher;

import cn.zhxu.toys.util.DigestUtils;
import org.apache.commons.codec.binary.Base64;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;



/**
 * 
 * @author Administrator
 *
 */
public class ZLDecryptor implements Decryptor {


	private String secret;
	
	
	@Override
	public void init(String secret) {
		this.secret = secret;
	}

	
	@Override
	public byte[] decrypt(byte[] cipherBytes) {
		return decrypt(secret.getBytes(StandardCharsets.UTF_8), cipherBytes);
	}
	

	@Override
	public byte[] decrypt(byte[] secretBytes, byte[] cipherBytes) {
		try {
			if (cipherBytes.length % 2 == 0) {
				throw new RuntimeException("不可解析的密文：" + Arrays.toString(cipherBytes));
			}
			secretBytes = DigestUtils.toMd5(secretBytes);
			int mod = cipherBytes[0];
			byte[] textBytes = new byte[(cipherBytes.length - 1) / 2];
			for (int i = 0; i < textBytes.length; i++) {
				int left = cipherBytes[2 * i + 1];
				int right = cipherBytes[2 * i + 2];
				int sum = right * 2 + left - mod;
				byte secertByte = secretBytes[i % secretBytes.length];
				textBytes[i] = (byte) (sum - secertByte);
			}
			return textBytes;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public String decrypt(String cipherText) {
		return decrypt(secret, cipherText);
	}
	
	@Override
	public String decrypt(String secret, String cipherText) {
		byte[] cipherBytes = Base64.decodeBase64(cipherText);
		byte[] textBytes = decrypt(secret.getBytes(StandardCharsets.UTF_8), cipherBytes);
		return new String(textBytes, StandardCharsets.UTF_8);
	}

	
}
